<?php
/**
 * 客户端
 *
 * User: Ken.Zhang <kenphp@yeah.net>
 * Date: 2019/9/22
 * Time: 20:54
 */
namespace OpenSDK\HaoDanKu;

use OpenSDK\HaoDanKu\Libs\Format;
use OpenSDK\HaoDanKu\Libs\Http;
use OpenSDK\HaoDanKu\Interfaces\Request;

class Client
{

    /**
     * 接口地址
     *
     * @var string
     */
    public $gateway = 'http://v2.api.haodanku.com';

    /**
     * AppKey
     *
     * @var string
     */
    public $appKey;
    
    /**
     * request对象
     * 
     * @var object
     */
    public $request;

    /**
     * 数据类型
     *
     * @var string
     */
    public $format = 'json';

    public function __construct($appKey='')
    {
        $this->appKey = $appKey;
    }
    
    /**
     * 设置请求对象
     * 
     * @var object
     */
    public function setRequest(Request $request)
    {
        $this->request = $request;
    }

    /**
     * 执行
     *
     * @return mixed
     */
    public function execute()
    {
        $requestUrl = $this->gateway . $this->request->method;
        $params     = $this->request->getParams();
        $params['apikey'] = $this->appKey;

        if (strtolower($this->request->requestType)=='post') {
            $result = Http::post($requestUrl, $params);
        } else {
            $query = $this->buildQueryParams($params);
            $result = Http::get($requestUrl . '/' . $query, []);
        }

        return strtolower($this->format)=='json' ? Format::deJSON($result) : Format::deSimpleXML($result);
    }

    /**
     * Get参数构建
     *
     * @param array $data
     * @return string
     */
    private function buildQueryParams($data)
    {
        $query = [];
        foreach($data as $key=>$item)
        {
            $query[] = $key;
            $query[] = $item;
        }

        return implode('/', $query);
    }



}